<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LLM 聊天界面</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* CSS 变量定义 - 现代化配色方案 */
        :root {
            --primary-color: #667eea;
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --secondary-color: #f093fb;
            --user-bubble: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --user-bubble-text: #ffffff;
            --bot-bubble: #ffffff;
            --bot-bubble-text: #2d3748;
            --bot-bubble-shadow: 0 2px 8px rgba(0,0,0,0.1);
            --error-bubble: #fed7d7;
            --error-text: #e53e3e;
            --background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            --sidebar-bg: linear-gradient(180deg, #2d3748 0%, #1a202c 100%);
            --sidebar-hover-bg: rgba(255,255,255,0.1);
            --header-height: 70px;
            --footer-height: 80px;
            --border-radius: 16px;
            --shadow-light: 0 4px 6px rgba(0, 0, 0, 0.05);
            --shadow-medium: 0 8px 25px rgba(0, 0, 0, 0.1);
            --shadow-heavy: 0 20px 40px rgba(0, 0, 0, 0.15);
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        /* 基础样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif;
            background: var(--background);
            height: 100vh;
            overflow: hidden;
            font-size: 14px;
            line-height: 1.6;
            color: #2d3748;
        }

        /* 主布局 */
        .main-layout {
            display: flex;
            height: 100vh;
            position: relative;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: 280px;
            background: var(--sidebar-bg);
            color: #e2e8f0;
            display: flex;
            flex-direction: column;
            padding: 20px 16px;
            flex-shrink: 0;
            box-shadow: var(--shadow-medium);
            position: relative;
            z-index: 10;
        }

        .new-chat-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            width: 100%;
            padding: 14px 16px;
            border: 2px solid rgba(255, 255, 255, 0.2);
            border-radius: var(--border-radius);
            background: rgba(255, 255, 255, 0.05);
            color: #e2e8f0;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: var(--transition);
            backdrop-filter: blur(10px);
        }

        .new-chat-btn:hover {
            background: var(--sidebar-hover-bg);
            border-color: rgba(255, 255, 255, 0.3);
            transform: translateY(-1px);
            box-shadow: var(--shadow-light);
        }

        .new-chat-btn i {
            font-size: 16px;
        }
        .history-list {
            flex-grow: 1;
            overflow-y: auto;
            margin-top: 24px;
            padding-right: 8px;
        }

        .history-list::-webkit-scrollbar {
            width: 4px;
        }

        .history-list::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 2px;
        }

        .history-list::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.3);
            border-radius: 2px;
            transition: var(--transition);
        }

        .history-list::-webkit-scrollbar-thumb:hover {
            background: rgba(255, 255, 255, 0.5);
        }

        .history-list ul {
            list-style: none;
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .history-list li a {
            display: block;
            text-decoration: none;
            color: #cbd5e0;
            padding: 12px 16px;
            border-radius: 12px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            transition: var(--transition);
            font-size: 13px;
            font-weight: 400;
            position: relative;
        }

        .history-list li a:hover {
            background: var(--sidebar-hover-bg);
            color: #e2e8f0;
            transform: translateX(4px);
        }

        .history-list li a.active {
            background: rgba(255, 255, 255, 0.15);
            color: #ffffff;
            font-weight: 500;
        }

        .history-list li a.active::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 3px;
            height: 20px;
            background: var(--secondary-color);
            border-radius: 0 2px 2px 0;
        }

        /* 会话项容器样式 */
        .conversation-item {
            display: flex;
            align-items: center;
            position: relative;
            border-radius: 12px;
            transition: var(--transition);
        }

        .conversation-item:hover {
            background: var(--sidebar-hover-bg);
        }

        .conversation-item:hover .delete-conversation-btn {
            opacity: 1;
            visibility: visible;
        }

        /* 删除按钮样式 */
        .delete-conversation-btn {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(239, 68, 68, 0.8);
            border: none;
            border-radius: 6px;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 10px;
            cursor: pointer;
            opacity: 0;
            visibility: hidden;
            transition: all 0.2s ease;
            z-index: 10;
        }

        .delete-conversation-btn:hover {
            background: rgba(239, 68, 68, 1);
            transform: translateY(-50%) scale(1.1);
        }

        /* 调整会话链接样式以为删除按钮留出空间 */
        .conversation-item a {
            flex: 1;
            padding-right: 40px !important;
        }
        .user-profile {
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            padding-top: 20px;
            margin-top: 20px;
            position: relative;
        }

        .user-info {
            display: flex;
            align-items: center;
            padding: 12px 16px;
            border-radius: 12px;
            cursor: pointer;
            transition: var(--transition);
            background: rgba(255, 255, 255, 0.05);
            backdrop-filter: blur(10px);
        }

        .user-info:hover {
            background: var(--sidebar-hover-bg);
            transform: translateY(-1px);
            box-shadow: var(--shadow-light);
        }

        .user-info .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: var(--primary-gradient);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            margin-right: 12px;
            flex-shrink: 0;
            font-size: 16px;
            box-shadow: var(--shadow-light);
        }

        .user-info .username {
            font-weight: 500;
            flex-grow: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            color: #e2e8f0;
            font-size: 14px;
        }
        .settings-menu {
            position: absolute;
            bottom: calc(100% + 12px);
            left: 0;
            width: 100%;
            background: rgba(45, 55, 72, 0.95);
            backdrop-filter: blur(20px);
            border-radius: var(--border-radius);
            box-shadow: var(--shadow-heavy);
            padding: 12px;
            z-index: 100;
            display: none;
            border: 1px solid rgba(255, 255, 255, 0.1);
            animation: slideUp 0.2s ease-out;
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .settings-menu.show {
            display: block;
        }

        .settings-menu a {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            color: #e2e8f0;
            text-decoration: none;
            border-radius: 8px;
            transition: var(--transition);
            font-size: 14px;
            font-weight: 400;
        }

        .settings-menu a:hover {
            background: rgba(255, 255, 255, 0.1);
            color: #ffffff;
            transform: translateX(4px);
        }

        .settings-menu a i {
            width: 18px;
            text-align: center;
            font-size: 16px;
        }

        /* 聊天容器样式 */
        .chat-container {
            flex-grow: 1;
            height: 100%;
            display: flex;
            flex-direction: column;
            background: #ffffff;
            position: relative;
        }

        .chat-header {
            height: var(--header-height);
            background: var(--primary-gradient);
            color: white;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 32px;
            flex-shrink: 0;
            box-shadow: var(--shadow-medium);
            position: relative;
            z-index: 5;
        }

        .chat-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            z-index: -1;
        }

        .chat-header h1 {
            font-size: 1.5rem;
            font-weight: 700;
            background: linear-gradient(45deg, #ffffff, #f0f8ff);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .header-controls {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .clear-btn {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
            cursor: pointer;
            font-size: 14px;
            padding: 8px 16px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: var(--transition);
            font-weight: 500;
            backdrop-filter: blur(10px);
        }

        .clear-btn:hover {
            background: rgba(255, 255, 255, 0.2);
            border-color: rgba(255, 255, 255, 0.3);
            transform: translateY(-1px);
            box-shadow: var(--shadow-light);
        }

        .mode-select {
            width: 140px;
            padding: 8px 16px;
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            background: rgba(255, 255, 255, 0.1);
            color: white;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: var(--transition);
            backdrop-filter: blur(10px);
        }

        .mode-select:hover {
            background: rgba(255, 255, 255, 0.2);
            border-color: rgba(255, 255, 255, 0.3);
        }

        .mode-select option {
            background: #2d3748;
            color: #e2e8f0;
            padding: 8px;
        }

        /* 聊天消息区域样式 */
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 24px 32px;
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            position: relative;
        }

        .chat-messages::-webkit-scrollbar {
            width: 6px;
        }

        .chat-messages::-webkit-scrollbar-track {
            background: rgba(0, 0, 0, 0.05);
            border-radius: 3px;
        }

        .chat-messages::-webkit-scrollbar-thumb {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 3px;
            transition: var(--transition);
        }

        .chat-messages::-webkit-scrollbar-thumb:hover {
            background: rgba(0, 0, 0, 0.3);
        }

        .message-row {
            display: flex;
            margin-bottom: 20px;
            max-width: 85%;
            animation: fadeInUp 0.3s ease-out;
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .message-row .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #cbd5e0;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 16px;
            flex-shrink: 0;
            font-size: 18px;
            box-shadow: var(--shadow-light);
        }

        .message-row.bot .avatar {
            background: var(--primary-gradient);
            color: white;
        }

        .message-row.error .avatar {
            background: linear-gradient(135deg, #fc8181 0%, #e53e3e 100%);
            color: white;
        }

        .message-bubble {
            padding: 16px 20px;
            border-radius: 20px;
            line-height: 1.6;
            word-wrap: break-word;
            font-size: 15px;
            position: relative;
            max-width: 100%;
        }

        .message-bubble.user {
            background: var(--user-bubble);
            color: var(--user-bubble-text);
            border-bottom-right-radius: 6px;
            box-shadow: var(--shadow-medium);
        }

        .message-bubble.bot {
            background: var(--bot-bubble);
            color: var(--bot-bubble-text);
            border-bottom-left-radius: 6px;
            box-shadow: var(--bot-bubble-shadow);
            border: 1px solid rgba(0, 0, 0, 0.05);
        }

        .message-bubble.error {
            background: var(--error-bubble);
            color: var(--error-text);
            border: 1px solid #fc8181;
            border-bottom-left-radius: 6px;
            box-shadow: var(--shadow-light);
        }

        .message-row.user {
            margin-left: auto;
            flex-direction: row-reverse;
        }

        .message-row.user .avatar {
            margin-right: 0;
            margin-left: 16px;
            background: var(--user-bubble);
        }

        .message-row.user .message-bubble {
            text-align: left;
        }
        /* 打字指示器 */
        .typing-indicator {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 8px 0;
        }

        .typing-indicator .dot {
            width: 10px;
            height: 10px;
            margin: 0 4px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 50%;
            animation: typing 1.4s infinite ease-in-out;
            box-shadow: var(--shadow-light);
        }

        .typing-indicator .dot:nth-child(2) {
            animation-delay: 0.2s;
        }

        .typing-indicator .dot:nth-child(3) {
            animation-delay: 0.4s;
        }

        @keyframes typing {
            0%, 80%, 100% {
                transform: scale(0.8);
                opacity: 0.5;
            }
            40% {
                transform: scale(1.2);
                opacity: 1;
            }
        }

        /* 聊天输入区域样式 */
        .chat-input-area {
            padding: 20px 32px 24px;
            background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
            border-top: 1px solid rgba(0, 0, 0, 0.08);
            display: flex;
            align-items: center;
            flex-shrink: 0;
            min-height: var(--footer-height);
            position: relative;
        }

        .chat-input-area::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 1px;
            background: linear-gradient(90deg, transparent, rgba(0, 0, 0, 0.1), transparent);
        }

        .input-wrapper {
            width: 100%;
            display: flex;
            align-items: flex-end;
            background: #ffffff;
            border: 2px solid #e2e8f0;
            border-radius: 24px;
            padding: 12px 16px;
            transition: var(--transition);
            box-shadow: var(--shadow-light);
            position: relative;
            overflow: hidden;
        }

        .input-wrapper::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
            opacity: 0;
            transition: var(--transition);
            z-index: 0;
        }

        .input-wrapper:focus-within {
            border-color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1), var(--shadow-medium);
            transform: translateY(-2px);
        }

        .input-wrapper:focus-within::before {
            opacity: 1;
        }
        #userInput {
            flex-grow: 1;
            border: none;
            outline: none;
            resize: none;
            font-family: inherit;
            font-size: 15px;
            line-height: 1.6;
            max-height: 120px;
            overflow-y: auto;
            background: transparent;
            color: #2d3748;
            position: relative;
            z-index: 1;
            padding: 4px 0;
        }

        #userInput::placeholder {
            color: #a0aec0;
            font-weight: 400;
        }

        #sendBtn {
            background: var(--primary-gradient);
            color: white;
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            font-size: 18px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            margin-left: 12px;
            transition: var(--transition);
            box-shadow: var(--shadow-medium);
            position: relative;
            z-index: 1;
        }

        #sendBtn:hover {
            transform: translateY(-2px) scale(1.05);
            box-shadow: var(--shadow-heavy);
        }

        #sendBtn:active {
            transform: translateY(0) scale(0.95);
        }

        #sendBtn:disabled {
            background: linear-gradient(135deg, #cbd5e0 0%, #a0aec0 100%);
            cursor: not-allowed;
            opacity: 0.6;
            transform: none;
            box-shadow: var(--shadow-light);
        }

        /* 文件上传按钮样式 */
        #attachBtn {
            background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
            color: white;
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            font-size: 18px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            margin-left: 8px;
            transition: var(--transition);
            box-shadow: var(--shadow-medium);
            position: relative;
            z-index: 1;
        }

        #attachBtn:hover {
            background: linear-gradient(135deg, #38a169 0%, #2f855a 100%);
            transform: translateY(-2px) scale(1.05);
            box-shadow: var(--shadow-heavy);
        }

        #attachBtn:active {
            transform: translateY(0) scale(0.95);
        }

        #attachBtn:disabled {
            background: linear-gradient(135deg, #cbd5e0 0%, #a0aec0 100%);
            cursor: not-allowed;
            opacity: 0.6;
            transform: none;
            box-shadow: var(--shadow-light);
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .sidebar {
                width: 260px;
                transform: translateX(-100%);
                transition: var(--transition);
                position: fixed;
                height: 100vh;
                z-index: 1000;
            }

            .sidebar.show {
                transform: translateX(0);
            }

            .chat-messages {
                padding: 16px 20px;
            }

            .chat-input-area {
                padding: 16px 20px 20px;
            }

            .message-row {
                max-width: 95%;
            }

            .chat-header {
                padding: 0 20px;
            }

            .chat-header h1 {
                font-size: 1.25rem;
            }
        }

    </style>
</head>
<body>

    <div class="main-layout">
        <div class="sidebar">
            <button class="new-chat-btn" id="newChatBtn"><i class="fa-solid fa-plus"></i> 新建聊天</button>
            <div class="history-list">
                <ul>
                    <li><a href="#" class="active">今天：关于Python的有趣事实</a></li>
                    <li><a href="#">昨天：如何规划一次完美的旅行</a></li>
                </ul>
            </div>
            <div class="user-profile">
                <div id="settings-menu" class="settings-menu">
                    <a href="#"><i class="fa-solid fa-gear"></i> 系统设置</a>
                    <a href="#" id="logout-link"><i class="fa-solid fa-right-from-bracket"></i> 退出登录</a>
                </div>
                <div class="user-info" id="user-info-trigger">
                    <div class="avatar">U</div>
                    <span class="username">用户名</span>
                </div>
            </div>
        </div>

        <div class="chat-container">
            <header class="chat-header">
                <h1>LLM Chat</h1>
                <div class="header-controls">
                    <button id="clearBtn" class="clear-btn"><i class="fa-solid fa-trash-can"></i><span>清空</span></button>
                    <select id="chatType" class="mode-select">
                        <option value="gpt-4">知识库</option>
                        <option value="gpt-3.5-turbo">GPT-3.5</option>
                    </select>
                </div>
            </header>

            <main id="chatMessages" class="chat-messages"></main>

            <footer class="chat-input-area">
                <div class="input-wrapper">
                    <textarea id="userInput" placeholder="输入消息... (Shift + Enter 换行)" rows="1"></textarea>
                    <input type="file" id="fileInput" style="display:none" accept=".pdf,.doc,.docx" />
                    <button id="attachBtn" title="上传文件" type="button">
                        <i class="fa-solid fa-paperclip"></i>
                    </button>
                    <button id="sendBtn" title="发送消息" disabled>
                        <i class="fa-solid fa-paper-plane"></i>
                    </button>
                </div>
            </footer>
        </div>
    </div>


<script>
        document.addEventListener('DOMContentLoaded', function() {
            // 添加页面加载动画
            document.body.style.opacity = '0';
            setTimeout(() => {
                document.body.style.transition = 'opacity 0.5s ease-in-out';
                document.body.style.opacity = '1';
            }, 100);
            // --- DOM Element Selection ---
            const chatMessages = document.getElementById('chatMessages');
            const userInput = document.getElementById('userInput');
            const sendBtn = document.getElementById('sendBtn');
            const attachBtn = document.getElementById('attachBtn');
            const fileInput = document.getElementById('fileInput');
            const clearBtn = document.getElementById('clearBtn');
            const newChatBtn = document.getElementById('newChatBtn');
            const historyList = document.querySelector('.history-list ul');
            const usernameSpan = document.querySelector('.username');
            const avatarDiv = document.querySelector('.avatar');
            const userInfoTrigger = document.getElementById('user-info-trigger');
            const settingsMenu = document.getElementById('settings-menu');
            const logoutLink = document.getElementById('logout-link');

            // --- State Management ---
            let conversations = []; // 会话列表将从服务器加载
            let conversationId = null;
            let messages = [];
            let isLoading = false;

            // --- UI Interaction Logic ---
            userInfoTrigger.addEventListener('click', (event) => {
                event.stopPropagation();
                settingsMenu.classList.toggle('show');
            });
            window.addEventListener('click', () => settingsMenu.classList.remove('show'));
            settingsMenu.addEventListener('click', (event) => event.stopPropagation());
            userInput.addEventListener('input', () => {
                userInput.style.height = 'auto';
                userInput.style.height = (userInput.scrollHeight) + 'px';
                updateSendDisabled();
            });

            // --- Core Functions ---
            function updateSendDisabled() {
                sendBtn.disabled = isLoading || (!userInput.value.trim() && fileInput.files.length === 0);
                attachBtn.disabled = isLoading;
            }

            function scrollToBottom() {
                setTimeout(() => { chatMessages.scrollTop = chatMessages.scrollHeight; }, 10);
            }

            // --- Conversation Management ---
            async function loadConversations() {
                const username = localStorage.getItem('username');
                if (!username) return;

                try {
                    const response = await fetch(`/api/sessions/conversations?username=${encodeURIComponent(username)}`);
                    if (response.ok) {
                        const data = await response.json();
                        conversations = data.conversations.map(conv => ({
                            id: conv.id,
                            title: conv.title,
                            messages: [] // 消息将在切换会话时加载
                        }));
                        renderHistory();
                    } else {
                        console.error('加载会话列表失败:', response.statusText);
                        conversations = [];
                    }
                } catch (error) {
                    console.error('加载会话列表出错:', error);
                    conversations = [];
                }
            }

            function renderHistory() {
                historyList.innerHTML = '';
                conversations.forEach(conv => {
                    const li = document.createElement('li');
                    const conversationItem = document.createElement('div');
                    conversationItem.className = 'conversation-item';

                    const a = document.createElement('a');
                    a.href = '#';
                    a.textContent = conv.title;
                    if (conv.id === conversationId) a.classList.add('active');
                    a.addEventListener('click', (e) => {
                        e.preventDefault();
                        switchConversation(conv.id);
                    });

                    // 添加删除按钮
                    const deleteBtn = document.createElement('button');
                    deleteBtn.className = 'delete-conversation-btn';
                    deleteBtn.innerHTML = '<i class="fas fa-trash"></i>';
                    deleteBtn.title = '删除会话';
                    deleteBtn.addEventListener('click', (e) => {
                        e.stopPropagation();
                        deleteConversation(conv.id);
                    });

                    conversationItem.appendChild(a);
                    conversationItem.appendChild(deleteBtn);
                    li.appendChild(conversationItem);
                    historyList.appendChild(li);
                });
            }

            async function switchConversation(id) {
                conversationId = id;
                renderHistory(); // 更新侧边栏的活跃状态

                // 显示加载状态
                messages = [{ sender: 'system', text: '正在加载聊天历史...' }];
                renderMessages();

                try {
                    // 从数据库加载历史消息
                    await loadConversationMessages(id);
                } catch (error) {
                    console.error('加载聊天历史失败:', error);
                    messages = [{ sender: 'bot', text: '您好！欢迎使用 LLM 聊天机器人。请选择一个聊天模式，然后开始提问吧！' }];
                    renderMessages();
                }

                scrollToBottom();
            }

            async function loadConversationMessages(conversationId) {
                const username = localStorage.getItem('username');
                if (!username) {
                    messages = [{ sender: 'bot', text: '您好！欢迎使用 LLM 聊天机器人。请选择一个聊天模式，然后开始提问吧！' }];
                    renderMessages();
                    return;
                }

                try {
                    const response = await fetch(`/api/sessions/conversations/${conversationId}/messages?username=${encodeURIComponent(username)}`);
                    if (response.ok) {
                        const data = await response.json();

                        if (data.messages && data.messages.length > 0) {
                            // 转换消息格式
                            messages = data.messages.map(msg => ({
                                sender: msg.sender === 'user' ? 'user' : 'bot',
                                text: msg.content
                            }));
                        } else {
                            // 如果没有历史消息，显示欢迎消息
                            messages = [{ sender: 'bot', text: '您好！欢迎使用 LLM 聊天机器人。请选择一个聊天模式，然后开始提问吧！' }];
                        }

                        renderMessages();
                    } else {
                        console.error('加载消息失败:', response.statusText);
                        messages = [{ sender: 'bot', text: '您好！欢迎使用 LLM 聊天机器人。请选择一个聊天模式，然后开始提问吧！' }];
                        renderMessages();
                    }
                } catch (error) {
                    console.error('加载消息出错:', error);
                    messages = [{ sender: 'bot', text: '您好！欢迎使用 LLM 聊天机器人。请选择一个聊天模式，然后开始提问吧！' }];
                    renderMessages();
                }
            }

            async function createConversation() {
                const username = localStorage.getItem('username');
                if (!username) {
                    console.error('用户未登录');
                    return;
                }

                try {
                    const response = await fetch(`/api/sessions/conversations/create?username=${encodeURIComponent(username)}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ title: '新的聊天' })
                    });

                    if (response.ok) {
                        const data = await response.json();
                        const newConv = {
                            id: data.conversation_id,
                            title: data.title,
                            messages: []
                        };
                        conversations.unshift(newConv);
                        switchConversation(data.conversation_id);
                        renderHistory();
                    } else {
                        console.error('创建会话失败:', response.statusText);
                    }
                } catch (error) {
                    console.error('创建会话出错:', error);
                }
            }

            async function deleteConversation(targetConversationId) {
                const username = localStorage.getItem('username');
                if (!username) {
                    console.error('用户未登录');
                    return;
                }

                if (!confirm('确定要删除这个会话吗？此操作不可撤销。')) {
                    return;
                }

                try {
                    const response = await fetch(`/api/sessions/conversations/delete?username=${encodeURIComponent(username)}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ conversation_id: targetConversationId })
                    });

                    if (response.ok) {
                        // 从本地列表中移除
                        conversations = conversations.filter(conv => conv.id !== targetConversationId);

                        // 如果删除的是当前会话，切换到第一个会话或创建新会话
                        if (targetConversationId === conversationId) {
                            if (conversations.length > 0) {
                                switchConversation(conversations[0].id);
                            } else {
                                await createConversation();
                            }
                        }

                        renderHistory();
                    } else {
                        const errorData = await response.json();
                        alert('删除会话失败: ' + (errorData.detail || '未知错误'));
                    }
                } catch (error) {
                    console.error('删除会话出错:', error);
                    alert('删除会话时发生错误');
                }
            }

            function clearChat() {
                // 清空当前会话的消息
                messages = [{ sender: 'bot', text: '您好！欢迎使用 LLM 聊天机器人。请选择一个聊天模式，然后开始提问吧！' }];
                renderMessages();
                scrollToBottom();

                // 注意：实际的数据库清空将在下次API调用时通过会话历史管理器处理
            }

            // --- Message Rendering ---
            function addMessage(sender, text) {
                messages.push({ sender, text });

                // 更新本地会话标题（如果是用户的第一条消息）
                const conv = conversations.find(c => c.id === conversationId);
                if (conv && (!conv.title || conv.title === '新的聊天') && sender === 'user') {
                    conv.title = text.slice(0, 30) + (text.length > 30 ? '...' : '');
                    renderHistory();
                }

                renderMessages();
                scrollToBottom();

                // 添加消息出现动画
                const lastMessage = chatMessages.lastElementChild;
                if (lastMessage) {
                    lastMessage.classList.add('message-appear');
                }
            }

            function renderMessages() {
                chatMessages.innerHTML = '';
                messages.forEach(msg => {
                    const messageRow = document.createElement('div');
                    messageRow.className = `message-row ${msg.sender}`;

                    const bubble = document.createElement('div');
                    bubble.className = `message-bubble ${msg.sender}`;

                    if (msg.sender !== 'user') {
                        const avatar = document.createElement('div');
                        avatar.className = 'avatar';
                        const icon = document.createElement('i');
                        icon.className = msg.sender === 'bot' ? 'fas fa-comment-dots' : 'fas fa-exclamation-triangle';
                        avatar.appendChild(icon);
                        messageRow.appendChild(avatar);
                    }

                    // **FIX 1**: Added 'message-text' class to the content div
                    const content = document.createElement('div');
                    content.className = 'message-text';
                    content.textContent = msg.text;
                    bubble.appendChild(content);

                    messageRow.appendChild(bubble);
                    chatMessages.appendChild(messageRow);
                });

                if (isLoading && messages[messages.length - 1]?.sender !== 'bot') {
                    // This logic is simplified as the placeholder is now handled by streamAndRenderResponse
                }
            }

            // --- Streaming Logic ---
            async function streamAndRenderResponse(text) {
                addMessage('bot', ''); // Add empty bot message placeholder

                try {
                    const username = localStorage.getItem('username');
                    const response = await fetch('/api/submit', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            input: text,
                            conversation_id: conversationId,
                            username: username
                        })
                    });

                    if (!response.ok) throw new Error(`服务器错误: ${response.status}`);
                    if (!response.body) throw new Error("响应体不存在");

                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    let fullBotResponse = "";

                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;
                        const chunk = decoder.decode(value, { stream: true });
                        fullBotResponse += chunk;
                        appendChunkToLastMessage(chunk);
                        scrollToBottom();
                    }

                    const lastMessage = messages[messages.length - 1];
                    if (lastMessage && lastMessage.sender === 'bot') {
                        lastMessage.text = fullBotResponse;
                        // 消息已通过API自动保存到数据库，无需手动保存
                    }

                } catch (error) {
                    updateLastErrorBotMessage('请求失败: ' + error.message);
                    const lastMessage = messages[messages.length - 1];
                    if (lastMessage && lastMessage.sender === 'bot') {
                        lastMessage.sender = 'error';
                        lastMessage.text = '请求失败: ' + error.message;
                        // 错误消息不需要保存到数据库
                        renderMessages(); // Re-render to show the error style

                        // 添加错误动画
                        const lastMessageElement = chatMessages.lastElementChild;
                        if (lastMessageElement) {
                            lastMessageElement.classList.add('error-shake');
                        }
                    }
                }
            }

            function appendChunkToLastMessage(chunk) {
                // **FIX 2**: Corrected DOM selector
                const messageElements = document.querySelectorAll('.message-row.bot');
                if (messageElements.length > 0) {
                    const lastBotMessage = messageElements[messageElements.length - 1];
                    const textElement = lastBotMessage.querySelector('.message-text');
                    if (textElement) {
                        textElement.textContent += chunk;
                    }
                }
            }

            function updateLastErrorBotMessage(errorMessage) {
                const messageElements = document.querySelectorAll('.message-row.bot');
                if (messageElements.length > 0) {
                    const lastBotMessage = messageElements[messageElements.length - 1];
                    const textElement = lastBotMessage.querySelector('.message-text');
                    if (textElement) {
                        textElement.textContent = errorMessage;
                        lastBotMessage.parentElement.classList.remove('bot');
                        lastBotMessage.parentElement.classList.add('error');
                    }
                }
            }

            // --- Main Action Handlers ---
            async function sendMessage() {
                const text = userInput.value.trim();
                const hasFile = fileInput.files.length > 0;

                // 如果既没有文本也没有文件，则返回
                if (isLoading || (!text && !hasFile)) return;

                // 如果有文件，处理文件上传
                if (hasFile) {
                    await uploadFile(fileInput.files[0]);
                    // 清空文件输入
                    fileInput.value = '';
                    return;
                }

                // 处理文本消息
                await sendTextMessage(text);
            }

            async function sendTextMessage(text) {
                if (!text || isLoading) return;

                // 添加发送动画效果
                sendBtn.innerHTML = '<div class="loading-spinner"></div>';
                sendBtn.classList.add('message-sending');

                addMessage('user', text);
                userInput.value = '';
                userInput.style.height = 'auto';

                isLoading = true;
                updateSendDisabled();

                try {
                    await streamAndRenderResponse(text);
                } finally {
                    isLoading = false;
                    updateSendDisabled();

                    // 恢复发送按钮
                    sendBtn.innerHTML = '<i class="fa-solid fa-paper-plane"></i>';
                    sendBtn.classList.remove('message-sending');
                }
            }

            async function uploadFile(file) {
                if (!file) return;

                const allowedTypes = ['.pdf', '.doc', '.docx'];
                const fileExt = '.' + file.name.split('.').pop().toLowerCase();
                if (!allowedTypes.includes(fileExt)) {
                    addMessage('error', `不支持的文件类型：${fileExt}`);
                    return;
                }
                const maxSize = 10 * 1024 * 1024;
                if (file.size > maxSize) {
                    addMessage('error', `文件大小超过限制（最大10MB）`);
                    return;
                }

                isLoading = true;
                updateSendDisabled();

                const formData = new FormData();
                formData.append('file', file);

                try {
                    const uploadResponse = await fetch('/api/upload', {
                        method: 'POST',
                        body: formData
                    });
                    const data = await uploadResponse.json();

                    if (data.success) {
                        const extractedText = data.text_content;
                        if (extractedText && extractedText.trim()) {
                            // 直接发送完整的文件内容给机器人进行回答，不显示中间过程
                            await streamAndRenderResponse(extractedText);
                        } else {
                            addMessage('error', '文件中未找到可提取的文本内容');
                        }
                    } else {
                        addMessage('error', data.detail || '文件上传失败');
                    }
                } catch (error) {
                    addMessage('error', '文件上传失败: ' + error.message);
                } finally {
                    isLoading = false;
                    updateSendDisabled();
                }
            }

            // --- Event Listeners ---
            sendBtn.addEventListener('click', sendMessage);
            userInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && !e.shiftKey && !sendBtn.disabled) {
                    e.preventDefault();
                    sendMessage();
                }
            });
            attachBtn.addEventListener('click', () => fileInput.click());
            fileInput.addEventListener('change', () => {
                // 文件选择后更新发送按钮状态
                updateSendDisabled();
            });
            clearBtn.addEventListener('click', clearChat);
            newChatBtn.addEventListener('click', createConversation);
            logoutLink.addEventListener('click', (e) => {
                e.preventDefault();
                localStorage.removeItem('username');
                window.location.href = '/login';
            });

            // --- Initialization ---
            async function initializeApp() {
                const savedUsername = localStorage.getItem('username');
                if (savedUsername) {
                    usernameSpan.textContent = savedUsername;
                    avatarDiv.textContent = savedUsername.charAt(0).toUpperCase();

                    // 加载用户的会话历史
                    await loadConversations();

                    if (conversations.length === 0) {
                        await createConversation();
                    } else {
                        switchConversation(conversations[0].id);
                    }
                } else {
                    // In a real app, you might redirect: window.location.href = '/login';
                    console.log("未找到用户名，请先登录。");
                    // 创建一个临时会话用于演示
                    conversations = [{
                        id: Date.now().toString(),
                        title: '新的聊天',
                        messages: []
                    }];
                    switchConversation(conversations[0].id);
                }

                updateSendDisabled();
            }

            // 启动应用
            initializeApp();
        });
    </script>
</body>
</html>